/*
 * @Author: 糊涂的老知青
 * @Date: 2021-12-02
 * @Version: 1.0.0
 * @Description:
 */
package infra_domainservice

import (
	"lzq-admin/base/domainservice"
	infra_model "lzq-admin/internal/infrastructure/model"
	"lzq-admin/pkg/orm"
	"lzq-admin/pkg/utility"

	"github.com/gin-gonic/gin"

	"github.com/pkg/errors"
	"xorm.io/xorm"
)

// AuthPermissionDomainService 操作权限领域服务
type AuthPermissionDomainService struct {
	domainservice.BaseDomainService
}

func NewDSAuthPermission(c *gin.Context) *AuthPermissionDomainService {
	return &AuthPermissionDomainService{
		domainservice.BaseDomainService{
			GinCtx: c,
		},
	}
}

func (s *AuthPermissionDomainService) Insert(dbSession *xorm.Session, modelDto infra_model.CreateAuthPermissionDto) (result infra_model.AuthPermission, err error) {
	var entity infra_model.AuthPermission
	entity = infra_model.AuthPermission{
		AuthPermissionBase: infra_model.AuthPermissionBase{
			Code:   modelDto.Code,
			Name:   modelDto.Name,
			Rank:   modelDto.Rank,
			MenuId: modelDto.MenuId,
			Policy: modelDto.Policy,
		},
	}
	entity.ID = utility.UuidCreate()

	_, err = orm.NewLzqOrm(s.GinCtx).ISessionWithTrans(dbSession).Insert(&entity)
	if err != nil {
		dbSession.Rollback()
		return infra_model.AuthPermission{}, err
	}
	return entity, nil
}

func (s *AuthPermissionDomainService) Delete(dbSession *xorm.Session, menuId string) error {
	m := infra_model.AuthPermission{}
	if _, err := orm.NewLzqOrm(s.GinCtx).DSessionWithTrans(false, dbSession).Where("menuId = ?", menuId).Update(&m); err != nil {
		dbSession.Rollback()
		return err
	}
	return nil
}

func (s *AuthPermissionDomainService) Get(id string) (infra_model.AuthPermissionDto, error) {
	var dto infra_model.AuthPermissionDto
	has, err := orm.NewLzqOrm(s.GinCtx).QSession(false).ID(id).Where("IsDeleted = ?", false).Get(&dto)
	if err != nil {
		return dto, err
	}
	if has {
		return dto, nil
	} else {
		return dto, errors.New("操作权限不存在或已删除")
	}
}
